<template>
  <el-form-item v-bind="formItemProps">
    <slot>
      <jax-input v-model="data" v-bind="_inputAttr" v-on="inputOn || {}" />
      <span :class="['jax-form-item-tips']" v-if="tips">{{ tips }}</span>
    </slot>
  </el-form-item>
</template>

<script setup>
import _ from 'lodash-es'

const emits = defineEmits(['update:modelValue'])

// https://element-plus.org/zh-CN/component/form.html#formitem-attributes
const props = defineProps({
  modelValue: { type: [Object, String, Number, Boolean, Array] },
  tips: String,

  type: String, // 类型
  inputAttr: Object, // input属性
  inputOn: Object, // input事件
  options: { type: [Object, String, Number, Boolean, Array], default: null }, // 用于快速透传给Input
  placeholder: String, // 用于快速透传给Input
  rules: Array,
})

const attrs = useAttrs()

const data = computed({
  get: () => props.modelValue,
  set: (val) => emits('update:modelValue', val),
})

const formItemProps = computed(() => {
  let formItemProps = {
    prop: attrs.name || attrs.prop,
    ...attrs,
    rules: formItemRules.value,
    // labelWidth: attrs.labelWidth,
    // required: attrs.required,
    // error: attrs.error,
    // showMessage: attrs.showMessage,
    // inlineMessage: attrs.inlineMessage,
    // size: attrs.size,
    // for: attrs.for,
    // validateStatus: attrs.validateStatus,
  }

  return formItemProps
})

const _inputAttr = computed(() => {
  return {
    // 透传到input的字段
    type: props.type,
    options: props.options,
    placeholder: props.placeholder,
    // ...props.inputAttr,
    inputAttr: props.inputAttr,
  }
})

const formItemRules = computed(() => {
  const { label, name, required } = attrs
  const title = label || name

  let rules = Object.assign([], props.rules)

  if (required) {
    rules.unshift({
      required: true,
      message: `${title}不能为空`,
      trigger: 'blur',
    })
  }

  return rules
})
</script>

<style lang="scss" scoped></style>
